package com.itheima.document.interceptors;

import com.itheima.common.threadlocal.UserHolder;
import com.itheima.common.util.JsonUtils;
import com.itheima.common.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 拦截请求获取到Security上下文中用户信息
 **/
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取security上下文对象,通过上下文对象获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //获取认证后的用户信息json字符串
            String userinfoJson = (String) authentication.getPrincipal();
            //转为用户信息对象
            UserInfo userInfo = JsonUtils.toBean(userinfoJson, UserInfo.class);
            //存入Threadlocal
            UserHolder.setUserInfo(userInfo);
            return true;
        } catch (Exception e) {
            log.error("【系统微服务】-拦截器获取当前用户信息异常：{}", e.getMessage());
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
